import { Table, Button, Modal, message } from "antd"
import { EditOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import PropTypes from 'prop-types'
import { DeleteProductsFnc } from '@/api/goods'
import { itemType } from "./type";

const Tables = ({dataSource, init, ipt, current, pageSize, total, sizeCurrentChange, changeEditBox, changePageNow}: itemType) => {
 const columns = [
    {dataIndex: 'key', width: 50},
    {title: '商品名称', dataIndex: 'goods_name', key: 'goods_name', width: 400, ellipsis: true},
    {title: '商品价格', dataIndex: 'goods_price', key: 'goods_price', width: 70},
    {title: '商品重量', dataIndex: 'goods_weight', key: 'goods_weight', width: 70},
    {title: '创建时间', dataIndex: 'add_time', key: 'add_time',width: 120, ellipsis: true, render: (time: string) => createTime(time)},
    {title: '操作', width: 180, render: (info: {id: number, username: string, role_name: string}) => {
      return (
      <>
        <Button type='primary' size='small' icon={<EditOutlined/>} onClick={() => changeEditBox(true, info.id)}>编辑</Button> 
        <Button type="primary" danger size='small' icon={<DeleteOutlined/>} onClick={() => deleteUser(info.id)} style={{margin: '0 6px 0'}}>删除</Button> 
      </>
      )
    }}
 ]   

 // 创建时间
 const createTime = (time: string) => {
    const date = new Date(time)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1 + '').padStart(2, '0')
    const d = (date.getDate() + '').padStart(2, '0')
    const h = (date.getHours() + '').padStart(2, '0')
    const f = (date.getMinutes() + '').padStart(2, '0')
    const m = (date.getSeconds() + '').padStart(2, '0')
    return `${year}-${month}-${d} ${h}:${f}${m}`
 }

 // 删除用户
 const deleteUser = async (id: number) => {
   Modal.confirm({
    icon: <ExclamationCircleOutlined />,
    content: '此操作将永久删除用户, 是否继续?',
    onOk: async () => {
      const res = await DeleteProductsFnc(id)
      if(res.data.meta.status === 200) {
        message.success('删除成功', 1.5, () => {
          if(total % pageSize === 1) {
            changePageNow()
          } else {
            init(ipt, current, pageSize)
          }
        })
      }
    }
   })
 } 

 return (
    <Table dataSource={dataSource} columns={columns} bordered={true} scroll={{x:500}} 
    pagination={{current: current, pageSize: pageSize, total: total, pageSizeOptions: [2,5,10], showQuickJumper: true, showSizeChanger: true, onChange: sizeCurrentChange}}/>
  )
}

export default Tables
Tables.proTypes = {
    dataSource: PropTypes.bool.isRequired,
    changeEditBox: PropTypes.func.isRequired,
    total: PropTypes.number.isRequired,
    init: PropTypes.func.isRequired,
    ipt: PropTypes.string.isRequired,
    current: PropTypes.number.isRequired,
    pageSize: PropTypes.number.isRequired,
    sizeCurrentChange: PropTypes.func.isRequired,
    changePageNow: PropTypes.func.isRequired
}